/*
   Copyright 2009 Ryan Phillips

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
#include <apr.h>
#include <apr_network_io.h>
#include <apr_poll.h>
#include <apr_buckets.h>
#include <apr_strings.h>
#include <apr_signal.h>
#include <apr_thread_proc.h>
#include <apr_getopt.h> 
#include <iostream>
#include <sstream>
#include <error.h>
#include <sys/inotify.h>
#include "CoreMessage.pb.h"
#include "remotecores.h"

using namespace std;

typedef struct conn_baton_t {
    apr_socket_t *sock;
    apr_pool_t *pool;
} conn_baton_t;

static void serve(apr_pool_t *pool, const char *host, apr_port_t port);
static void usage(apr_pool_t *pool);

static const apr_getopt_option_t server_options[] = {
    {"hostname",  'n', 1, "hostname"},
    {"port",      'p', 1, "Port of server"},
    {0, 0, 0, 0},
};

int main(int argc, const char **argv)
{
    apr_pool_t *g_pool;
    apr_getopt_t *os;
    apr_status_t rv;
    int opt;
    const char *arg;
    const char *host = NULL;
    apr_port_t port = REMOTE_CORES_DEFAULT_PORT;

    /* Init */
    apr_initialize();
    apr_pool_create(&g_pool, NULL);

    /* Parse Commandline */
    rv = apr_getopt_init(&os, g_pool, argc, argv);
    if (rv != APR_SUCCESS) {
        char buffer[256];
        apr_strerror(rv, buffer, sizeof(buffer));
        error(rv, 0, "apr_getopt_init : %s", buffer);
    }

    while (1) {
        rv = apr_getopt_long(os, server_options, &opt, &arg);
        if (APR_STATUS_IS_EOF(rv)) {
            break;
        }

        if (rv != APR_SUCCESS) {
            usage(g_pool);
        }

        switch (opt) {
        case 'n':
            host = arg;
            break;
        case 'p':
            port = atoi(arg);
            break;
        }
    }

    if (host == NULL) {
        usage(g_pool);
    }

    fprintf(stderr, "remotecore-server: Listening (%s:%i)\n", host, port);

    /* Run */
    serve(g_pool, host, port);

    /* Cleanup */
    apr_pool_destroy(g_pool);
    apr_terminate();

    return 0;
}

static void * APR_THREAD_FUNC serve_thread(apr_thread_t *tid, void *data)
{
    conn_baton_t *conn = (conn_baton_t*) data;
    apr_uint32_t pb_length;
    apr_size_t len;
    apr_status_t rv;
    apr_file_t *file;
    apr_size_t nbytes, o, i;
    char header[sizeof(apr_uint32_t)];
    char core_buffer[8 * 1024];
    char *pb;
    CoreMessage msg;
    istringstream input;
    string pbstr;

    (void) tid;

    len = sizeof(header);
    rv = apr_socket_recv(conn->sock, header, &len);
    if (rv != APR_SUCCESS) {
        char buffer[256];
        apr_strerror(rv, buffer, sizeof(buffer));
        error(0, 0, "apr_socket_recv (header) : %s", buffer);
        goto done;
    }

    pb_length = ntohl(*(apr_uint32_t*)header);
    pb = (char*) apr_palloc(conn->pool, pb_length);

    len = pb_length;
    rv = apr_socket_recv(conn->sock, pb, &len);
    if (rv != APR_SUCCESS) {
        char buffer[256];
        apr_strerror(rv, buffer, sizeof(buffer));
        error(0, 0, "apr_socket_recv (pb) : %s", buffer);
        goto done;
    }

    pbstr.assign(pb, pb_length);
    input.str(pbstr);
    msg.ParseFromIstream(&input);

    fprintf(stderr, "remotecore-server: Writing Core (%s, %" APR_SIZE_T_FMT " bytes)\n",
            msg.filename().c_str(), msg.filesize());

    rv = apr_file_open(&file, msg.filename().c_str(), APR_WRITE | APR_CREATE, APR_FPROT_OS_DEFAULT, 
                       conn->pool);
    if (rv != APR_SUCCESS) {
        char buffer[256];
        apr_strerror(rv, buffer, sizeof(buffer));
        error(0, 0, "apr_file_open (pb) : %s", buffer);
        goto done;
    }

    o = 0;
    i = msg.filesize();
    while (i > 0) {
        nbytes = sizeof(core_buffer);
        apr_socket_recv(conn->sock, core_buffer, &nbytes);
        if (rv != APR_SUCCESS) {
            char buffer[256];
            apr_strerror(rv, buffer, sizeof(buffer));
            error(rv, 0, "%s", buffer);
        }

        apr_file_write(file, core_buffer, &nbytes);

        o +=  nbytes;
        i -= nbytes;
    } 

    apr_file_close(file);

done:
    apr_socket_close(conn->sock);
    apr_pool_destroy(conn->pool);
    return NULL;
}

static void serve(apr_pool_t *pool, const char *host, apr_port_t port)
{
    apr_socket_t *sock;
    apr_sockaddr_t *sa;
    apr_status_t rv;

    rv = apr_sockaddr_info_get(&sa, host, APR_INET, port, 0, pool);   
    if (rv != APR_SUCCESS) {
        char buffer[256];
        apr_strerror(rv, buffer, sizeof(buffer));
        error(rv, 0, "apr_sockaddr_info_get : %s", buffer);
    }

    rv = apr_socket_create(&sock, APR_INET, SOCK_STREAM, APR_PROTO_TCP, pool);   
    if (rv != APR_SUCCESS) {
        char buffer[256];
        apr_strerror(rv, buffer, sizeof(buffer));
        error(rv, 0, "apr_socket_create : %s", buffer);
    }

    apr_socket_opt_set(sock, APR_SO_REUSEADDR, 1);

    rv = apr_socket_bind(sock, sa);
    if (rv != APR_SUCCESS) {
        char buffer[256];
        apr_strerror(rv, buffer, sizeof(buffer));
        error(rv, 0, "apr_socket_bind : %s", buffer);
    }

    apr_socket_listen(sock, 7);

    apr_signal(SIGPIPE, SIG_IGN);   

    while (1) {
        conn_baton_t *baton;
        apr_threadattr_t *tattr;
        apr_thread_t *tid;
        apr_socket_t *usock;
        apr_pool_t *connection_pool;

        apr_pool_create(&connection_pool, NULL);

        rv = apr_socket_accept(&usock, sock, connection_pool);

        baton = (conn_baton_t*) apr_palloc(connection_pool, sizeof(*baton));
        baton->sock = usock;
        baton->pool= connection_pool;

        rv = apr_threadattr_create(&tattr, connection_pool);
        rv = apr_threadattr_detach_set(tattr, 1); 

        apr_thread_create(&tid, tattr, serve_thread, baton, connection_pool);
    }
}

static void usage(apr_pool_t *pool)
{
    (void) pool;
    fprintf(stderr, "remotecore-server -n [BIND IP/Hostname] [-p Port]\n");
    exit(EXIT_FAILURE);
}
